//
//  SAInventoryListDetailVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/21.
//

#import "SAInventoryListDetailVC.h"
#import "SASaleDocumentsHeaderView.h"
#import "SAWarehousingDetailCell.h"
#import "SAStockInvoiceDetailAPI.h"
#import "SASalesOrderViewListModel.h"
#import "YBImageBrowser.h"

@interface SAInventoryListDetailVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate,YBImageBrowserDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *userLab;
@property (nonatomic, strong) UILabel *dateLab;
@property (nonatomic, strong) UILabel *remarkLab;
@property (nonatomic, strong) UILabel *totalLab;
@property (nonatomic, strong) NSString *checkFlowNo;
@property (nonatomic, strong) SAStockInvoiceDetailAPI *stockInvoiceDetailAPI;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) UIView *grayView2;//标题头
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, strong) UIImageView *statusImageV;

@end

@implementation SAInventoryListDetailVC

-(instancetype)initWithCheckFlowNo:(NSString *)checkFlowNo {
    if (self = [super init]) {
        self.checkFlowNo = checkFlowNo;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.stockInvoiceDetailAPI == api) {
        self.userLab.text = data[@"data"][@"stockCheckEmpName"];
        self.dateLab.text = data[@"data"][@"stockCheckTime"];
        NSString *remark = data[@"data"][@"remark"];
        if (remark && remark.length > 0) {
            self.remarkLab.text = remark;
        }
        NSString *checkStatus = data[@"data"][@"checkStatus"];
        if ([checkStatus isEqualToString:@"1"]) {
            self.statusImageV.image = [UIImage imageNamed:@"statusImage_1"];
        }else {
            self.statusImageV.image = [UIImage imageNamed:@"statusImage_2"];
        }
        
        NSInteger num = 0;
        NSInteger lossNum = 0;
        NSArray *detailProductVOS = data[@"data"][@"detailProductVOS"];
        for (NSDictionary *productDic in detailProductVOS) {
            SASalesOrderViewListModel *model = [[SASalesOrderViewListModel alloc] init];
            model.productId = [NSString stringWithFormat:@"%@",productDic[@"productId"]];
            model.productCode = [NSString stringWithFormat:@"%@",productDic[@"productCode"]];
            model.productName = productDic[@"productName"];
            model.img = productDic[@"img"];
            model.imgList = productDic[@"imgList"];
            
            NSArray *skuForms = productDic[@"skuForms"];
            NSMutableArray *toPendSkuAttrs = [NSMutableArray array];
            for (NSDictionary *skuDic in skuForms) {
                SASalesOrderToPendSkuList *sku = [[SASalesOrderToPendSkuList alloc] init];
                sku.skuId = [NSString stringWithFormat:@"%@",skuDic[@"skuId"]];
                sku.count = [NSString stringWithFormat:@"%@",skuDic[@"beforeStock"]];
                sku.stock = [NSString stringWithFormat:@"%@",skuDic[@"afterStock"]];
                sku.subtotal = [NSString stringWithFormat:@"%@",skuDic[@"diffStock"]];
                sku.colourId = [NSString stringWithFormat:@"%@",skuDic[@"colourId"]];
                sku.colourName = [NSString stringWithFormat:@"%@",skuDic[@"colourName"]];
                sku.sizeId = [NSString stringWithFormat:@"%@",skuDic[@"sizeId"]];
                sku.sizeName = [NSString stringWithFormat:@"%@",skuDic[@"sizeName"]];
                [toPendSkuAttrs addObject:sku];
                num += [sku.stock integerValue];
                lossNum += ([sku.stock integerValue] - [sku.count integerValue]);
            }
            model.toPendSkuAttrs = toPendSkuAttrs;
            [self.dataMarr addObject:model];
        }
        
        self.totalLab.text = [NSString stringWithFormat:@"已盘:%zd款,%zd件,盈亏:%zd件",self.dataMarr.count,num,lossNum];
        [self.tableView reloadData];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
 
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].toPendSkuAttrs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAWarehousingDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAWarehousingDetailCell" forIndexPath:indexPath];
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].toPendSkuAttrs[indexPath.row];
    cell.productModel = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SASaleDocumentsHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SASaleDocumentsHeaderView"];
    SASalesOrderViewListModel *model = self.dataMarr[section];
    header.saleModel = model;
    WeakSelf
    header.imageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.5);
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    self.grayView2.hidden = y < kScaleNum(180);
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:self.checkFlowNo];
    [self setBgImage:nil];
    
    UIView *headerView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 215)];
    headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headerView];
    
    NSArray *arr = @[@"  盘点人", @"  日期", @"  备注"];
    NSArray *iconArr = @[@"Sale_user", @"Warehousing_icon_4", @"Warehousing_icon_5"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.frame = CGRectMake(kScaleNum(20), kScaleNum(45 * i), kScaleNum(80), kScaleNum(45));
        [titleBtn setTitle:arr[i] forState:UIControlStateNormal];
        [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        titleBtn.titleLabel.font = kFont(15);
        [titleBtn setImage:[UIImage imageNamed:iconArr[i]] forState:UIControlStateNormal];
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [headerView addSubview:titleBtn];
        
        UILabel *contentLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(220), kScaleNum(45 * i), kScaleNum(200), kScaleNum(45))];
        contentLab.font = kFont(15);
        contentLab.textAlignment = NSTextAlignmentRight;
        contentLab.textColor = kLightgGrayColor;
        [headerView addSubview:contentLab];
        
        if (i == 0) {
            self.userLab = contentLab;
        }else if (i == 1) {
            self.dateLab = contentLab;
        }else if (i == 2) {
            self.remarkLab = contentLab;
        }
        
        if (i < 4) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(45 * i + 44.5), kScreenWidth - kScaleNum(40), kScaleNum(0.5))];
            line.backgroundColor = kBgColor;
            [headerView addSubview:line];
        }
    }
    
    UILabel *totalLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(45 * 3), kScaleNum(300), kScaleNum(45))];
    totalLab.font = kFont(15);
    totalLab.textAlignment = NSTextAlignmentLeft;
    totalLab.textColor = kBlackColor;
    [headerView addSubview:totalLab];
    totalLab.text = @"1款,5件";
    self.totalLab = totalLab;
    
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(45 * 4), kScreenWidth, kScaleNum(35))];
    grayView.backgroundColor = kTextBgColor;
    [headerView addSubview:grayView];
    NSArray *arr2 = @[@"商品", @"当前库存", @"盘点数", @"盈亏数"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kGrayColor;
        [grayView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(150), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(225), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(300), 0, kScaleNum(70), kScaleNum(35));
        }
    }
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = headerView;
    
    self.stockInvoiceDetailAPI.stockCheckFlowId = self.checkFlowNo;
    [self.stockInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    UIView *grayView2 = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight)-0.5, kScreenWidth, kScaleNum(35))];
    grayView2.backgroundColor = kColor(228, 231, 243, 1);
    grayView2.hidden = YES;
    [self.view addSubview:grayView2];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kGrayColor;
        [grayView2 addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(150), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(225), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(300), 0, kScaleNum(70), kScaleNum(35));
        }
    }
    self.grayView2 = grayView2;
    
    [headerView addSubview:self.statusImageV];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASaleDocumentsHeaderView class] forHeaderFooterViewReuseIdentifier:@"SASaleDocumentsHeaderView"];
        [_tableView registerClass:[SAWarehousingDetailCell class] forCellReuseIdentifier:@"SAWarehousingDetailCell"];
    }
    return _tableView;
}

-(SAStockInvoiceDetailAPI *)stockInvoiceDetailAPI {
    if (!_stockInvoiceDetailAPI) {
        _stockInvoiceDetailAPI = [SAStockInvoiceDetailAPI apiWithDelegate:self];
    }
    return _stockInvoiceDetailAPI;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(UIImageView *)statusImageV {
    if (!_statusImageV) {
        _statusImageV = [[UIImageView alloc] initWithFrame:SARectMake(270, 75, 100, 100)];
        _statusImageV.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _statusImageV;
}

@end
